﻿using System;
using System.IO;
using Faml;
using Faml.Compiler;
using Faml.Frontend;

public class TextFileCommand : ExternalCommand
{
    public TextFileCommand() : base("textfile")
        { /* Nothing to do here */ }

    public override void Parse(Parser parser, RuntimeEnvironment runtime)
    {
        object fileNameObj = FamlProgram.Evaluate(runtime, runtime.Precompile(parser));
        string fileName = fileNameObj.ToString();
        if (!parser.MatchDelimiter("{"))
            throw new Exception("Syntax error in file content definition");
        parser.MoveNext();
        StreamWriter sw = new StreamWriter(fileName);
        while (true)
        {
            PrintHelper.Print(sw,runtime.Precompile(parser));
            if (parser.MatchDelimiter("}")) {
                parser.MoveNext();
                break;
            } else if(parser.MatchDelimiter(","))
                parser.MoveNext();
            else
                throw new Exception("Syntax error in write command");
        }
        sw.Close();
    }
}